/**
 * 
 */
package com.wolfpire.system.common;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;

import com.wolfpire.system.model.Authority;
import com.wolfpire.system.model.User;

/**
 * 权限工具类
 * @author lihd
 *
 */
public class AuthorityUtils {
	
	/**
	 * 判断用户菜单的操作权限
	 * @param user	用户
	 * @param menuId	菜单Id
	 * @return
	 */
	public static List<Authority> getAperAuthorities(User user, Long menuId) {
		List<Authority> operAuthorities = new ArrayList<Authority>();
		List<Authority> userAuthorities = user.getUserAuthorities();
		Map<String, Object> temp = new HashMap<String, Object>();
		for(Authority authority : userAuthorities){
			if(temp.get(authority.getId().toString())==null){
				temp.put(authority.getId().toString(), "1");
				if(Authority.TYPE_OPERATOR.equals(authority.getType()) && menuId.equals(authority.getParentId())){
					operAuthorities.add(authority);
				}
			}
		}
		return operAuthorities;
	}
	
	/**
	 * 从list中获取authority的上级
	 * @param authorities	权限集合
	 * @param authority		目标权限
	 * @param map			
	 * 		Map<Long, Authority>	讲权限的id和对象作为键值对，用来提高重复遍历效率
	 * 		null 表示代码段中只查询一次父级
	 * @return
	 */
	public static Authority getParentAuth(List<Authority> authorities, Authority authority, Map<Long, Authority> map) {
		Authority a = null;
		if (null == map) {
			// 从list中遍历查询
			for (Authority auth : authorities) {
				if (authority.getParentId().equals(auth.getId())) {
					a = auth;
					break;
				}
			}
		} else {
			// 先从map中获取
			a = map.get(authority.getId());
			if (null == a) {
				// 从list中遍历查询
				for (Authority auth : authorities) {
					map.put(auth.getId(), auth);
					if (authority.getParentId().equals(auth.getId())) {
						a = auth;
						break;
					}
				}
			}
		}
		
		return a;
	}
	
	/**
	 * 深度获取authority的子节点
	 * @param authorities	权限集合
	 * @param authority		目标权限
	 * @param childrenCount	权限计数，用来提高重复遍历效率
	 * 			null 表示当前代码段只要一次递归查询即可
	 * 		
	 */
	public static void getChildren(List<Authority> authorities, Authority authority, Map<Long, Integer> childrenCount) {
		if (CollectionUtils.isEmpty(authorities)) {
			return;
		}
		Long oId = authority.getId();
		// 当authroity id不为空，且有子节点时候才去获取子节点
		if (null != oId) {
//			List<Authority> children = authority.getChildrenAuthories();
			if (null != childrenCount && null == childrenCount.get(oId)) {
				return;
			}
			List<Authority> children = authority.getChildren();
			for (Authority a : authorities) {
				if (null != a.getParentId()
						&& oId.equals(a.getParentId())) {
					if (!children.contains(a)) {
						// 获取a 的子节点
						getChildren(authorities, a, childrenCount);
						children.add(a);
					}
				}
			}
		}
		
	}
}
